package com.swyc.osschat.Common.Result;


import com.swyc.osschat.Common.Exception.ErrorCode;
import com.swyc.osschat.Common.Exception.SysErrorCode;

import java.io.Serializable;

/**
 * @author yanyipeng.ykw@foxmail.com
 * @date 2019/1/27 15:01
 */
public class Result<T> implements Serializable {

    /**
     * 响应状态码
     */
    private int code = 200;

    /**
     * 响应提示信息
     */
    private String message;

    /**
     * 响应结果对象
     */
    private T data;

    Result(int code, String message, T data){
        this.code=code;
        this.message=message;
        this.data=data;
    }

    public Result(int code, String message) {
        this(code, message, null);
    }

    public Result(int code, T date) {
        this(code, null, date);
    }

    public Result(String message) {
        this(0,message,null);
    }

    public Result() {
    }

    public Result(T data) {
        this(0,null,data);
    }

    public Result(ErrorCode errorCode){
        this.code = errorCode.getCode();
        this.message = errorCode.getMessage();
    }
    public Result(ErrorCode errorCode, T data){
        this.code = errorCode.getCode();
        this.message = errorCode.getMessage();
        this.data = data;
    }
    public Result(int code){
        this(code, SysErrorCode.getMsg(code), null);
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Object getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public boolean isSuccess(){
        return code == 200;
    }


    @Override
    public String toString() {
        return "Result{" +
                "code=" + code +
                ", message='" + message + '\'' +
                ", data=" + data +
                '}';
    }

    /**
     * 根据status返回错误编码
     *
     * @param status
     * @return
     */
    public static <T> Result<T> error(int status) {
        return new Result<T>(status);
    }

    public static <T> Result<T> error(String message) {
        Result<T> result = new Result<T>(500, message);
        return result;
    }

    public static <T> Result<T> badRequest() {
        Result<T> result = new Result<T>(400, "");
        return result;
    }
}
